<?php

namespace app\web\logic;

use app\common\component\Param;
use app\web\mongo\BackendUser;
use app\common\component\ErrorCode;

/**
 * 用户通用操作
 * Class BackendUserLogic
 * @package app\web\logic
 */
class BackendUserLogic
{
    public function userLogin()
    {
        $backendUser = BackendUser::getInstance()->find(['email' => Param::$validParams['email']]);
        if (empty($backendUser)) {
            throw new \Exception('此邮箱尚未注册', ErrorCode::RESPONSE_FAIL);
        }

        if (password_verify(Param::$validParams['password'], $backendUser['password']) == false) {
            throw new \Exception('密码错误', ErrorCode::RESPONSE_FAIL);
        }

        return $backendUser;
    }

    /**
     * 添加用户
     * @return mixed
     */
    public function addUser()
    {
        $backendUserValid = BackendUser::getInstance()->find(['email' => Param::$validParams['email']]);
        if ($backendUserValid) {
            throw new \Exception('此邮箱已经注册了', ErrorCode::RESPONSE_FAIL);
        }

        $data = [
            'nickname' => Param::$validParams['nickname'],
            'email' => Param::$validParams['email'],
            'password' => password_hash(Param::$validParams['password'], PASSWORD_BCRYPT),
            'login_ip' => request()->ip(),
            'token' => '',
            'createtime' => time(),
            'logintime' => 0,
        ];

        return BackendUser::getInstance()->add($data);
    }

    /** 忘记密码 */
    public function forgetUser()
    {
        $backendUser = BackendUser::getInstance()->find(['email' => Param::$validParams['email']]);
        if (empty($backendUser)) {
            throw new \Exception('此邮箱未注册', ErrorCode::RESPONSE_FAIL);
        }

        $data = ['password' => password_hash(Param::$validParams['password'], PASSWORD_BCRYPT)];
        return BackendUser::getInstance()->update($data, ['id' => $backendUser['id']]);
    }
}